package com.seeyon.apps.ddkk.form.workflowevent;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.seeyon.apps.ddkk.dao.QiangsDao;
import com.seeyon.apps.ddkk.manager.DDKkDistributorManger;
import com.seeyon.apps.ddkk.manager.QiangsDDManager;
import com.seeyon.apps.kk.constants.Constants;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormDataSubBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumBean;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.workflow.event.AbstractWorkflowEvent;
import com.seeyon.ctp.workflow.event.WorkflowEventData;
import com.seeyon.ctp.workflow.event.WorkflowEventResult;

public class CheckKeyMemberEvent  extends AbstractWorkflowEvent {
	
	private static final Log log = LogFactory.getLog(GenerateWordEvent.class);
	private FormApi4Cap4 formApi4Cap4;
	private QiangsDao qiangsDao;
	private QiangsDDManager qiangsDDManager;
	private EnumManager enumManagerNew;
	
	public void setEnumManagerNew(EnumManager enumManagerNew) {
		this.enumManagerNew = enumManagerNew;
	}
	public void setQiangsDao(QiangsDao qiangsDao) {
		this.qiangsDao = qiangsDao;
	}
	public void setFormApi4Cap4(FormApi4Cap4 formApi4Cap4) {
		this.formApi4Cap4 = formApi4Cap4;
	}
	public void setQiangsDDManager(QiangsDDManager qiangsDDManager) {
		this.qiangsDDManager = qiangsDDManager;
	}
	
	@Override
	public ApplicationCategoryEnum getAppName() {
		return ApplicationCategoryEnum.form;
	}
	
	@Override
	public String getId() {
		// TODO Auto-generated method stub
		return "20190114";
	}
	@Override
	public String getLabel() {
		// TODO Auto-generated method stub
		return "关键人员简历校验-处理前事件";
	}
	
	@Override
    public WorkflowEventResult onBeforeFinishWorkitem(WorkflowEventData data) {
		Map<Integer, List<FormDataMasterBean>> map = new HashMap<Integer, List<FormDataMasterBean>>();
		List<FormDataMasterBean> yesList = new ArrayList<FormDataMasterBean>();
		List<FormDataMasterBean> noList = new ArrayList<FormDataMasterBean>();
		List<FormDataMasterBean> reList = new ArrayList<FormDataMasterBean>();
		List<FormDataMasterBean> removeList = new ArrayList<FormDataMasterBean>();
		Map<Long, String> nameMap = new HashMap<Long, String>();
		
		String ret = "";
		WorkflowEventResult res = new WorkflowEventResult();
		FormBean formBean = (FormBean) data.getBusinessData().get("formBean");
		FormDataMasterBean formDataBean = (FormDataMasterBean) data.getBusinessData().get("formDataBean");
		//经销商填写节点增加手机号邮箱校验
		try {
			//邮箱手机号码格式校验
			DDKkDistributorManger kkDistributor=(DDKkDistributorManger) AppContext.getBean("kkDistributor");
			String checkResult=kkDistributor.mailAndPhoneCheck(formBean, formDataBean);
			if(!"".equals(checkResult)){
				res.setAlertMessage(checkResult);
				return res;
			}
		} catch (Exception e1) {
			log.error("ddkk邮箱手机号校验", e1);
			res.setAlertMessage("邮箱手机号校验异常,不能发起!");
			return res;
		}
		
		try {
			FormBean keyBean = formApi4Cap4.getFormByFormCode(Constants.keyMemberCode);
			//获取流程中有效关键人员对应的底表数据
			Map<Long, FormDataMasterBean> param = qiangsDDManager.findRelationKeyMember(formBean, formDataBean);
			for (FormTableBean subTable : formBean.getTableList()) {
				if (subTable.getDisplay().contains("关键人员简历")) {
					List<FormDataSubBean> formDataSubBean = formDataBean.getSubData(subTable.getTableName());
					for(FormDataSubBean subData: formDataSubBean){
						for(Long id : param.keySet()){
							if(subData.getId().equals(id)){
								nameMap.put(id, param.get(id).getFieldValue(
										keyBean.getFieldBeanByDisplay("姓名").getName()).toString());
								Long itemId = subData.getFieldValue(formBean.getFieldBeanByDisplay("关键人员-状态").getName()) == null ? null :
									(Long) subData.getFieldValue(formBean.getFieldBeanByDisplay("关键人员-状态").getName());
								if(null == param.get(id).getFieldValue(
										keyBean.getFieldBeanByDisplay("出生年月").getName())) {
									if(isContains(yesList, param.get(id), keyBean)){
										reList.add(param.get(id));
										subData.addFieldValue(formBean.getFieldBeanByDisplay("关键人员-状态").getName(),
												getItemByValue(itemId, "4"));
									} else {
										noList.add(param.get(id));
										subData.addFieldValue(formBean.getFieldBeanByDisplay("关键人员-状态").getName(),
												getItemByValue(itemId, "3"));
									}
								} else {
									yesList.add(param.get(id));
									subData.addFieldValue(formBean.getFieldBeanByDisplay("关键人员-状态").getName(),
											getItemByValue(itemId, "2"));
								}
								break;
							}
						}
					}

					for(FormDataMasterBean data1 : noList){
						if(isContains(yesList, data1, keyBean)){
							removeList.add(data1);
							Boolean isBreak = false;
							for(FormDataSubBean subData: formDataSubBean){
								for(Long id : param.keySet()){
									if(id.equals(subData.getId()) && param.get(id).equals(data1)){
										Long itemId = subData.getFieldValue(formBean.getFieldBeanByDisplay("关键人员-状态").getName()) == null ? null :
											(Long) subData.getFieldValue(formBean.getFieldBeanByDisplay("关键人员-状态").getName());
										subData.addFieldValue(formBean.getFieldBeanByDisplay("关键人员-状态").getName(),
												getItemByValue(itemId, "4"));
										isBreak = true;
										break;
									}
								}
								if(isBreak){
									break;
								}
							}
						}
					}
					break;
				}
			}
			if(CollectionUtils.isNotEmpty(noList)){
				for(FormDataMasterBean subData : noList){
					if(removeList.contains(subData)){
						continue;
					}
					String fieldName = keyBean.getFieldBeanByDisplay("姓名").getName();
					if(Strings.isEmpty(ret)){
						ret = subData.getFieldValue(fieldName).toString();
					} else {
						ret += " ," + subData.getFieldValue(fieldName).toString();
					}
				}
			}
			
			List<Map> list = new ArrayList<Map>();
			for(FormTableBean subTable : formBean.getTableList()) {
				if (subTable.getDisplay().contains("关键人员简历")) {
					List<FormDataSubBean> formDataSubBean = formDataBean.getSubData(subTable.getTableName());
					for(FormDataSubBean subData: formDataSubBean){
						Long itemId = subData.getFieldValue(formBean.getFieldBeanByDisplay("关键人员-状态").getName()) == null ? null :
							(Long) subData.getFieldValue(formBean.getFieldBeanByDisplay("关键人员-状态").getName());
						Map params = new HashMap();
						params.put("table", subTable.getTableName());
						params.put("field", formBean.getFieldBeanByDisplay("关键人员-状态").getName());
						params.put("value", itemId);
						params.put("id", subData.getId());
						params.put("keyName", formBean.getFieldBeanByDisplay("关键人员简历姓名").getName());
						params.put("keyValue", nameMap.get(subData.getId()));
						list.add(params);
					}
					break;
				}
			}
			List<Map> finalList = list;
			Thread thread = new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					try {
						Thread.sleep(30*1000L);
						for(Map map: finalList){
							qiangsDao.updateAgentStatus(map);
						}
					} catch (BusinessException e) {
						// TODO Auto-generated catch block
						log.error("##强生客开: ", e);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						log.error("##强生客开: ", e);
					}
				}
			});
			thread.start();

			if(Strings.isNotBlank(ret)){
				res.setAlertMessage("请完成 " + ret + " 的简历填写,否则不能提交!");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("##强生客开: ", e);
			res.setAlertMessage("校验关键人员简历是否填写异常!");
		} 
		return res;
	}
	
	private BigDecimal getItemByValue(Long itemId, String value){
		if(null == itemId){
			try {
				List<CtpEnumBean> item = enumManagerNew.getAllOrgCtpEnum(Constants.DEFAULT_ACCOUNT_ID);
				for(CtpEnumBean bean : item){
					if("状态".equals(bean.getEnumname())){
						for(CtpEnumItem it : bean.getItems()){
							if(it.getEnumvalue().equals(value)){
								return new BigDecimal(it.getId());
							}
						}
						break;
					}
				}
			} catch (BusinessException e) {
				// TODO Auto-generated catch block
				log.error("##强生客开: ", e);
			}
		}
		try {
			CtpEnumItem item = enumManagerNew.getCtpEnumItem(itemId);
			CtpEnumBean enums = enumManagerNew.getEnum(item.getRefEnumid());
			for(CtpEnumItem it : enums.getItems()){
				if(it.getEnumvalue().equals(value)){
					return new BigDecimal(it.getId());
				}
			}
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			log.error("##强生客开: ", e);
		}
		return null;
	}
	
	private boolean isContains(List<FormDataMasterBean> list, FormDataMasterBean data2, FormBean formBean){
		String fieldName = formBean.getFieldBeanByDisplay("姓名").getName();
		boolean isContains = false;
		for(FormDataMasterBean data1 : list){
			if(data1.getFieldValue(fieldName).equals(data2.getFieldValue(fieldName))){
				isContains = true;
				break;
			}
		}
		return isContains;
	}
}
